import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import moment from 'moment';
import _ from 'lodash';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  DatePicker,
  Button,
  Table,
  message,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { MonthPicker } = DatePicker;
const { Item } = Form;

const today = new Date();
const { pathname } = window.location;

interface TrajectoryProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  location: { query: any };
}

interface TrajectoryState {
  rowId:number;
  searchValues: any;
}

@connect(({
  trajectoryList: { dataInfo },
  loading,
}: any) => ({
  dataInfo,
  loading: loading.effects['trajectoryList/fetch'],
}))

class TrajectoryElem extends Component<TrajectoryProps, TrajectoryState> {
  columns = [
    { title: '操作人', dataIndex: 'staffName' },
    { title: '手机号', dataIndex: 'phone' },
    { title: '柜体编号', dataIndex: 'cabCode' },
    { title: '格口编号', dataIndex: 'cellCode' },
    { title: '快递单号', dataIndex: 'expCode' },
    { title: '操作类型', dataIndex: 'operationName' },
    { title: '操作来源', dataIndex: 'sourceName' },
    { title: '操作结果', dataIndex: 'resultName' },
    { title: '设备操作时间', dataIndex: 'time' },
    { title: '服务器时间', dataIndex: 'createTime' },
  ];

  state: TrajectoryState = {
    rowId: 0,
    searchValues: {
      cabCode: '',
      startTime: `${moment(today).format('YYYY-MM')}-01`,
      cellCode: '',
      expCode: '',
      phone: '',
      pageIndex: 1,
      pageSize: 20,
    },
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...values } = query;

    if (query && query.code) {
      return {
        searchValues: {
          ...values,
          cabCode: query.cabCode || query.code,
          pageIndex: Number(pageIndex) || 1,
          pageSize: Number(pageSize) || 20,
        },
      };
    }
    message.error('柜体编码不存在');
    return null;
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues } = this.state;
    const {
      location: { query: { id } },
    } = this.props;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || id !== prevProps.location.query.id
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const {
      searchValues: {
        pageIndex, pageSize, code, ...values
      },
    } = this.state;
    const params = this.turnValuesType(values);
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(params);
  };

  turnValuesType = (values: any) => ({
    // 转换数据类型
    ...values,
    startTime: moment(values.startTime || today),
  });

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues } = this.state;
    return {
      ...searchValues,
      startTime: `${moment(searchValues.startTime || today).format('YYYY-MM')}-01`,
    };
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { cellCode = '' } = values;
      if (Number.isNaN(cellCode) || cellCode.indexOf('.') >= 0) {
        message.error('柜体编号请输入正整数!');
        return;
      }

      const { location: { query } } = this.props;
      const params = {
        ...query,
        ...values,
        startTime: `${moment(values.startTime || query.startTime).format('YYYY-MM')}-01`,
        pageIndex: 1,
        pageSize: 20,
      };
      router.push({ pathname, query: params });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields(['expCode', 'cellCode', 'phone']);

    const { location: { query: { code } } } = this.props;
    router.push({ pathname, query: { code } });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };
    router.push({ pathname, query });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = `trajectoryList/${typeName}`;
    dispatch({ type, payload });
  };

  render() {
    const {
      searchValues: { pageIndex, pageSize },
    } = this.state;
    const {
      dataInfo,
      form: { getFieldDecorator },
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="柜体编号" colon={false}>
                  {getFieldDecorator('cabCode')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　　月份" colon={false}>
                  {getFieldDecorator('startTime')(
                    <MonthPicker
                      format="YYYY-MM"
                      placeholder="请选择月份"
                      style={{ width: '100%' }}
                    />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="快递单号" colon={false}>
                  {getFieldDecorator('expCode')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="格口编号" colon={false}>
                  {getFieldDecorator('cellCode')(
                    <Input allowClear type="number" placeholder="请输入" />,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12} justify="space-between">
              <Col md={6} sm={24}>
                <Item label="手机号码" colon={false}>
                  {getFieldDecorator('phone')(
                    <Input allowClear type="number" placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1200 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<TrajectoryProps>()(TrajectoryElem);
